﻿using Max.PH4.Shoppgin.Admin.Domain;
using Max.PH4.Shoppgin.Admin.DTO;
using Max.PH4.Shoppgin.Admin.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Max.PH4.Shoppgin.Admin.API.Controllers.Product
{
    /// <summary>
    /// 
    /// </summary>
    [Route("sku")]
    [ApiController]
    public class SKUController : ControllerBase
    {
        ISKUService _service;
        IWebHostEnvironment _host;

        public SKUController(ISKUService service, IWebHostEnvironment host)
        {
            _service = service;
            _host = host;
        }

        /// <summary>
        /// 添加SKU及相应的信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(ProductInputDto dto)
        {
            _service.AddSKU(dto);
            return Ok();
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload")]
        public IActionResult Upload()//(IFormFileCollection files)
        {
            ResponseResultDto result = new();

            //上传保存的文件以当天日期为目录进行保存
            var t = System.DateTime.Now.ToString("yyyyMMdd");
            var d = _host.WebRootPath + "/" + t;

            //创建目录
            if (!Directory.Exists(d))
            {
                Directory.CreateDirectory(d);
            }

            //获取文件
            var files = Request.Form.Files;
            if(files == null || files.Count <= 0)
            {
                result.Code = ResponseStateCode.Failed;
                result.Message = "请选择文件";
                return Ok(result);
            }

            List<string> list = new();
            foreach (var f in files)
            {
                //重命名文件。原文件是 ：afdafas.jpg，现文件：guid().jpg
                var newFileName = Guid.NewGuid().ToString("N");
                var ext = System.IO.Path.GetExtension(f.FileName);
                newFileName = newFileName + ext;
                var newFilePath = d+"/"+ newFileName;

                //保存文件
                using (var stream = new FileStream(newFilePath, FileMode.OpenOrCreate))
                {
                    f.CopyTo(stream);
                    list.Add(t + "/" + newFileName);
                }
            }
            result.Data = list;


            return Ok(result);
        }


        /// <summary>
        /// 批量修改
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdateAll(List<SKUEntity> entities)
        {

            _service.Update(entities);

            

            return Ok();
        }
    }
}
